<template>
  <div class="warehouse-management-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="12">
        <el-button icon="el-icon-plus" type="primary" @click="handleAdd">
          添加仓库
        </el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="12">
        <el-form :inline="true" :model="queryForm" @submit.native.prevent>
          <el-form-item>
            <el-input
              v-model.trim="queryForm.name"
              clearable
              placeholder="请输入仓库名称"
            />
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="queryData">
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table
    v-loading="listLoading"
      border
      :data="list"
      :element-loading-text="elementLoadingText"
      style="width: 100%"
      @selection-change="setSelectRows"
    >
      <el-table-column show-overflow-tooltip type="selection" />
      <el-table-column
        label="仓库ID"
        prop="id"
        show-overflow-tooltip
      />
      <el-table-column
        label="仓库名称"
        prop="name"
        show-overflow-tooltip
      />
      <el-table-column
        label="地址"
        prop="address"
        show-overflow-tooltip
      />
      <el-table-column
        label="管理员"
        prop="managerName"
        show-overflow-tooltip
      />
      <el-table-column label="状态" prop="status" show-overflow-tooltip width="100">
        <template #default="{ row }">
          <el-tag :type="statusTagType[row.status]">{{
            statusMap[row.status]
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="操作"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <el-button type="text" @click="handleEdit(row)">编辑</el-button>
          <el-button type="text" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNo"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />

    <!-- 仓库编辑弹窗 -->
    <el-dialog
      :title="dialogStatus === 'create' ? '新增仓库' : '编辑仓库'"
      :visible.sync="dialogVisible"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="warehouseForm"
        label-position="right"
        label-width="100px"
        :model="warehouseForm"
        :rules="rules"
      >
        <el-form-item label="仓库名称" prop="name">
          <el-input
            v-model="warehouseForm.name"
            placeholder="请输入仓库名称"
          />
        </el-form-item>
        <el-form-item label="仓库地址" prop="address">
          <el-input
            v-model="warehouseForm.address"
            placeholder="请输入仓库地址"
          />
        </el-form-item>
        <el-form-item label="管理员" prop="managerEmployeeId">
          <el-select
            v-model="warehouseForm.managerEmployeeId"
            clearable
            placeholder="请选择管理员"
            style="width: 100%;"
          >
            <el-option label="无" :value="null" />
            <el-option
              v-for="employee in availableEmployeesForManager"
              :key="employee.id"
              :label="employee.name"
              :value="employee.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="warehouseForm.status"
            placeholder="请选择状态"
            style="width: 100%;"
          >
            <el-option
              v-for="(label, value) in statusMap"
              :key="value"
              :label="label"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'WarehouseManagement', // Changed from BackToTop or Warehouse
  data() {
    return {
      list: [],
      allWarehouseData: [], // 存储所有仓库数据
      allEmployeesData: [], // 存储所有员工数据
      listLoading: true,
      layout: 'total, sizes, prev, pager, next, jumper',
      total: 0,
      selectRows: [],
      elementLoadingText: '正在加载...',
      queryForm: {
        pageNo: 1,
        pageSize: 10,
        name: '', // For filtering by warehouse name
      },
      dialogVisible: false,
      dialogStatus: 'create', // 'create' 或 'update'
      warehouseForm: {
        id: null,
        name: '',
        address: '',
        managerEmployeeId: null,
        status: 1, // Default to '正常使用'
      },
      rules: {
        name: [
          { required: true, message: '请输入仓库名称', trigger: 'blur' },
        ],
        status: [
          { required: true, message: '请选择仓库状态', trigger: 'change' },
        ],
      },
      statusMap: {
        1: '正常使用',
        2: '维护中',
        3: '已停用',
      },
      statusTagType: {
        1: 'success',
        2: 'warning',
        3: 'danger',
      },
    }
  },
  computed: {
    availableEmployeesForManager() {
      if (!this.allEmployeesData) return []
      // Employees who are not managing another warehouse OR are the current manager of the warehouse being edited
      return this.allEmployeesData.filter((employee) => {
        const isManagingAnotherWarehouse = this.allWarehouseData.some(
          (warehouse) =>
            warehouse.managerEmployeeId === employee.id && // Is manager of some warehouse
            warehouse.id !== this.warehouseForm.id // And that warehouse is not the one currently being edited
        )
        return !isManagingAnotherWarehouse
      })
    },
  },
  created() {
    this.loadEmployeeData()
    this.loadWarehouseData() // This will also call fetchData
  },
  methods: {
    loadEmployeeData() {
      const storedData = localStorage.getItem('employeeTableData')
      if (storedData) {
        this.allEmployeesData = JSON.parse(storedData)
      } else {
        this.allEmployeesData = [ // Default employee data if none in localStorage
            { id: 'emp001', name: '张三', warehouseId: 1, workStatus: 'on_duty', department: '技术部', position: '经理' },
            { id: 'emp002', name: '李四', warehouseId: 2, workStatus: 'on_duty', department: '销售部', position: '主管' },
            { id: 'emp003', name: '王五', warehouseId: null, workStatus: 'business_trip', department: '市场部', position: '专员' },
        ];
        this.saveEmployeeData(); // Save defaults
      }
    },
    saveEmployeeData() {
      localStorage.setItem('employeeTableData', JSON.stringify(this.allEmployeesData))
    },
    loadWarehouseData() {
      const storedData = localStorage.getItem('warehouseTableData')
      if (storedData) {
        this.allWarehouseData = JSON.parse(storedData)
      } else {
        // Default warehouse data if none in localStorage
        this.allWarehouseData = [
          { id: 1, name: '北京中心仓', address: '北京市朝阳区', managerEmployeeId: 'emp001', status: 1 },
          { id: 2, name: '上海配送中心', address: '上海市浦东新区', managerEmployeeId: 'emp002', status: 1 },
          { id: 3, name: '广州临时仓', address: '广州市天河区', managerEmployeeId: null, status: 2 },
        ]
        this.saveWarehouseData() // Save defaults
      }
      this.fetchData()
    },
    saveWarehouseData() {
      localStorage.setItem('warehouseTableData', JSON.stringify(this.allWarehouseData))
      // 触发事件，通知其他页面仓库数据已更新
      window.dispatchEvent(new CustomEvent('storageUpdated', { detail: { key: 'warehouseTableData' } }));
    },
    getEmployeeNameById(employeeId) {
      if (!employeeId || !this.allEmployeesData) return '无'
      const employee = this.allEmployeesData.find((emp) => emp.id === employeeId)
      return employee ? employee.name : '未知员工'
    },
    setSelectRows(val) {
      this.selectRows = val
    },
    handleAdd() {
      this.dialogStatus = 'create'
      this.resetForm()
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogStatus = 'update'
      this.warehouseForm = { ...row } // Copy row data to form
      this.dialogVisible = true
    },
    resetForm() {
      this.warehouseForm = {
        id: null,
        name: '',
        address: '',
        managerEmployeeId: null,
        status: 1,
      }
      if (this.$refs.warehouseForm) {
        this.$refs.warehouseForm.resetFields()
      }
    },
    submitForm() {
      this.$refs.warehouseForm.validate((valid) => {
        if (valid) {
          const newManagerId = this.warehouseForm.managerEmployeeId
          let oldManagerId = null
          let affectedWarehouseId = this.warehouseForm.id

          if (this.dialogStatus === 'create') {
            // 修改ID生成逻辑
            if (this.allWarehouseData && this.allWarehouseData.length > 0) {
              const maxId = this.allWarehouseData.reduce((max, warehouse) => warehouse.id > max ? warehouse.id : max, 0);
              this.warehouseForm.id = maxId + 1;
            } else {
              this.warehouseForm.id = 1; // 如果没有仓库，则从1开始
            }
            affectedWarehouseId = this.warehouseForm.id
            this.allWarehouseData.push({ ...this.warehouseForm })
            this.$message.success('新增仓库成功')
          } else {
            const index = this.allWarehouseData.findIndex(
              (item) => item.id === this.warehouseForm.id
            )
            if (index !== -1) {
              oldManagerId = this.allWarehouseData[index].managerEmployeeId // Get manager before update
              this.allWarehouseData.splice(index, 1, { ...this.warehouseForm })
              this.$message.success('更新仓库成功')
            }
          }

          // Linkage: Update employee's warehouseId if they become a manager
          // And unassign old manager if necessary
          if (newManagerId !== oldManagerId) {
            // If a new manager is assigned
            if (newManagerId) {
              const newManagerEmployee = this.allEmployeesData.find(emp => emp.id === newManagerId);
              if (newManagerEmployee) {
                // Assign new manager to this warehouse
                newManagerEmployee.warehouseId = affectedWarehouseId;

                // If this new manager was previously managing another warehouse, unassign them from the old one
                this.allWarehouseData.forEach(wh => {
                  if (wh.managerEmployeeId === newManagerId && wh.id !== affectedWarehouseId) {
                    wh.managerEmployeeId = null; // Unassign from old warehouse
                  }
                });
              }
            }
            // If there was an old manager and they are different from the new one
            if (oldManagerId && oldManagerId !== newManagerId) {
              const oldManagerEmployee = this.allEmployeesData.find(emp => emp.id === oldManagerId);
              if (oldManagerEmployee && oldManagerEmployee.warehouseId === affectedWarehouseId) {
                // If the old manager was working in this warehouse because they managed it,
                // and they are no longer the manager, unassign them from the warehouse.
                // This assumes managing a warehouse means working there.
                // A more complex logic might be needed if work assignment is separate.
                oldManagerEmployee.warehouseId = null;
              }
            }
            this.saveEmployeeData(); // Save changes to employees
          }

          this.saveWarehouseData()
          this.dialogVisible = false
          this.fetchData()
        }
      })
    },
    handleDelete(row) {
      // For simplicity, this example doesn't handle batch delete from selection
      if (row && row.id) {
        this.$baseConfirm('你确定要删除该仓库吗？', null, () => {
          const index = this.allWarehouseData.findIndex(
            (item) => item.id === row.id
          )
          if (index !== -1) {
            const deletedWarehouse = this.allWarehouseData[index];
            // Unlink manager if any
            if (deletedWarehouse.managerEmployeeId) {
              const manager = this.allEmployeesData.find(emp => emp.id === deletedWarehouse.managerEmployeeId);
              if (manager && manager.warehouseId === deletedWarehouse.id) {
                manager.warehouseId = null; // Unassign employee from this warehouse
                this.saveEmployeeData();
              }
            }
            this.allWarehouseData.splice(index, 1)
            this.saveWarehouseData()
            this.$message.success('删除成功')
            this.fetchData()
          }
        })
      } else {
         this.$baseMessage('请选择要删除的仓库', 'error');
      }
    },
    handleSizeChange(val) {
      this.queryForm.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.queryForm.pageNo = val
      this.fetchData()
    },
    queryData() {
      this.queryForm.pageNo = 1
      this.fetchData()
    },
    fetchData() {
      this.listLoading = true
      let filteredData = [...this.allWarehouseData]

      if (this.queryForm.name) {
        filteredData = filteredData.filter((item) =>
          item.name.toLowerCase().includes(this.queryForm.name.toLowerCase())
        )
      }

      // Add managerName to display
      const dataWithManagerName = filteredData.map((warehouse) => {
        return {
          ...warehouse,
          managerName: this.getEmployeeNameById(warehouse.managerEmployeeId),
        }
      })

      this.total = dataWithManagerName.length
      const start = (this.queryForm.pageNo - 1) * this.queryForm.pageSize
      const end = start + this.queryForm.pageSize
      this.list = dataWithManagerName.slice(start, end)

      setTimeout(() => {
        this.listLoading = false
      }, 300)
    },
  },
}
</script>

<style lang="scss" scoped>
.warehouse-management-container {
  padding: 20px;
}
</style>
